package com.learn.springcloud.hystrixexplainindetailconsumer.request.command.command;

import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;
import org.springframework.web.client.RestTemplate;
import rx.Observable;
import rx.Subscriber;

public class UserObservableCommand extends HystrixObservableCommand<String> {

    private String name;
    private RestTemplate restTemplate;

    public UserObservableCommand(HystrixCommandGroupKey group, RestTemplate restTemplate, String name) {
        super(group);
        this.name = name;
        this.restTemplate = restTemplate;
    }


    @Override
    protected Observable<String> construct() {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                if(!subscriber.isUnsubscribed()){
                    String url = "http://HYSTRIX-EXPLAIN-IN-DETAIL-PROVIDER/request/command/say/hello?name={1}";
                    String result = restTemplate.getForObject(url, String.class, name);
                    subscriber.onNext(name);
                    subscriber.onCompleted();
                }
            }
        });
    }

    @Override
    protected Observable<String> resumeWithFallback() {
        return Observable.error(new Exception("error, " + this.name));
    }

}
